﻿#include "chatroom.h"
#pragma execution_character_set("utf-8")


Chatroom::Chatroom(Operation::Opcode opcode) {
    this->opcode = opcode;
}

void Chatroom::init() {
    chatDesk = new QListWidget(this);
    chatDesk->setStyleSheet("background-color:#ffffff;"
                            "border:0px;"
                            "border-radius:15px;");
    voiceBtn = new QPushButton();
    voiceBtn->setIcon(QIcon(":/btnIcon/voice.png"));
    voiceBtn->setIconSize(QSize(35,35));
    voiceBtn->setStyleSheet("border:0px;background:transparent;");

    imgBtn = new QPushButton();
    imgBtn->setIcon(QIcon(":/btnIcon/picture.png"));
    imgBtn->setIconSize(QSize(35,35));
    imgBtn->setStyleSheet("border:0px;background:transparent;");

    fileBtn = new QPushButton();
    fileBtn->setIcon(QIcon(":/btnIcon/file.png"));
    fileBtn->setIconSize(QSize(35,35));
    fileBtn->setStyleSheet("border:0px;background:transparent;");

    textEdit = new QTextEdit();
    textEdit->setText("");
    textEdit->setStyleSheet("background-color:#ffffff;"
                            "border-color:#D3D3D3;"
                            "border-radius:20px;");

    emojiBtn = new QPushButton();
    emojiBtn->setIcon(QIcon(":/btnIcon/emoji.png"));
    emojiBtn->setIconSize(QSize(35,35));
    emojiBtn->setStyleSheet("border:0px;background:transparent;");

    sendBtn = new QPushButton();
    sendBtn->setText("发送");
    sendBtn->setStyleSheet("border-radius:25px;"
                           "font-weight:bold;"
                           "font-size:20px;"
                           "background-color:#6A5ACD;"
                           "border-width:0px;"
                           "color:white;");

    voiceBtn->setMaximumSize(50, 50);
    voiceBtn->setMinimumSize(50, 50);
    imgBtn->setMaximumSize(50, 50);
    imgBtn->setMinimumSize(50, 50);
    fileBtn->setMaximumSize(50, 50);
    fileBtn->setMinimumSize(50, 50);
    textEdit->setMaximumHeight(50);
    textEdit->setMinimumHeight(50);
    emojiBtn->setMaximumSize(50, 50);
    emojiBtn->setMinimumSize(50, 50);
    sendBtn->setMaximumSize(100, 50);
    sendBtn->setMinimumSize(100, 50);

    QHBoxLayout *hBoxLayout = new QHBoxLayout();
    hBoxLayout->addWidget(voiceBtn);
    hBoxLayout->addWidget(imgBtn);
    hBoxLayout->addWidget(fileBtn);
    hBoxLayout->addWidget(textEdit);
    hBoxLayout->addWidget(emojiBtn);
    hBoxLayout->addWidget(sendBtn);

    QVBoxLayout *vBoxLayout = new QVBoxLayout();
    vBoxLayout->addWidget(chatDesk);
    vBoxLayout->addLayout(hBoxLayout);
    this->setLayout(vBoxLayout);

    connect(imgBtn, SIGNAL(clicked()), this, SLOT(sendImgMsg()));
    connect(SGUN, SIGNAL(reSendImgMsg(InfoHead*, QByteArray, QHostAddress, quint16)),
            this, SLOT(reSendImgMsg(InfoHead*, QByteArray, QHostAddress, quint16)));

    connect(sendBtn, SIGNAL(clicked()), this, SLOT(sendTextMsg()));
    connect(SGUN,SIGNAL(reSendTextMsg(InfoHead*, QJsonDocument, QHostAddress, quint16)),
            this, SLOT(reSendTextMsg(InfoHead*, QJsonDocument, QHostAddress, quint16)));

    connect(voiceBtn,SIGNAL(clicked()),this,SLOT(sendVoiceMsg()));

    connect(emojiBtn, SIGNAL(clicked()), this, SLOT(clickEmojiBtn()));
    connect(fileBtn, SIGNAL(clicked()), this, SLOT(sendFileMsg()));
    connect(SGUN, SIGNAL(reSendGroupTextMsg(InfoHead*, QJsonDocument, QHostAddress, quint16)),
            this, SLOT(reSendGroupTextMsg(InfoHead*, QJsonDocument, QHostAddress, quint16)));
    connect(SGUN, SIGNAL(reSendFileMsg(InfoHead*, QByteArray, QHostAddress, quint16)),
            this, SLOT(reSendFileMsg(InfoHead*, QByteArray, QHostAddress, quint16)));
}

void Chatroom::sendVoiceMsg() {
    qDebug() << "SEND VOICE MSG";
    InfoHead * infoHead = new InfoHead(0, 0, opcode, Operation::Success,
                                       CONF.userId, reId,"");
    qDebug() << "reId" <<reId;
    QString voiceName = QString("%1-%2.mp3").arg(QString::number(CONF.userId),
                                              QString::number(20220325));

    addJsonTools.setChatRoomList(this->chatDesk);
    addJsonTools.changeJsonFile(CONF.userId,"voice",voiceName,infoHead->getDes(),infoHead->getSrc(),"history");
}

void Chatroom::sendTextMsg(){
    QString textContent = this->textEdit->toPlainText();
    this->textEdit->clear();
    QJsonDocument jsonDocument;
    QJsonObject jsonObject;
    jsonObject.insert("msg", textContent);
    jsonDocument.setObject(jsonObject);
    QByteArray bytes = jsonDocument.toJson();
    InfoHead * infoHead = new InfoHead(bytes.size(), 0, opcode, Operation::Success,
                                       CONF.userId, reId,"");
    TRANS->writeUdp(infoHead, bytes, CONF.serverIp, CONF.udpPort);
    if(opcode == Operation::SendTextMsg){
        addJsonTools.setChatRoomList(this->chatDesk);
        addJsonTools.changeJsonFile(CONF.userId, "text", textContent, infoHead->getDes(), infoHead->getSrc(),"history");
    }
    else if(opcode == Operation::SendGroupTextMsg){
        addJsonTools.setChatRoomList(this->chatDesk);
        addJsonTools.changeJsonFile(CONF.userId, "text", textContent, infoHead->getDes(), infoHead->getSrc(),"grouphistory");
    }

}

void Chatroom::reSendTextMsg(InfoHead *infoHead, QJsonDocument doc, QHostAddress ip, quint16 port){
    if (infoHead->getStateCode() == Operation::Fail) {
        qDebug() << "sendFail!!";
        return;
    }
    QJsonObject rootObj = doc.object();
    QString data = rootObj["msg"].toString();

    addJsonTools.setChatRoomList(this->chatDesk);
    addJsonTools.changeJsonFile(CONF.userId,"text",data,infoHead->getSrc(),infoHead->getSrc(),"history");
}

void Chatroom::reSendGroupTextMsg(InfoHead *infoHead, QJsonDocument doc, QHostAddress ip, quint16 port) {
    if (infoHead->getStateCode() == Operation::Fail) {
        qDebug() << "sendFail!!";
        return;
    }

    qDebug() << "receive GROUP MSG:::::::::::::";
    QJsonObject rootObj = doc.object();
    QString data = rootObj["msg"].toString();

    addJsonTools.setChatRoomList(this->chatDesk);
    addJsonTools.changeJsonFile(CONF.userId,"text",data,infoHead->getDes(),infoHead->getSrc(),"grouphistory");
//    emit SGUN->receiveMsg(infoHead->getSrc());
}

void Chatroom::chooseEmoji(QString emoji) {
    qDebug() << "emoji::::" <<emoji;
    this->textEdit->setText(this->textEdit->toPlainText()+emoji);
}

void Chatroom::clickEmojiBtn() {
    EmojiPanel *emojiPanel = new EmojiPanel();
    emojiPanel->show();
    connect(emojiPanel, SIGNAL(chooseEmoji(QString)), this, SLOT(chooseEmoji(QString)));
}

void Chatroom::sendImgMsg() {
    QFileInfo fileInfo(QFileDialog::getOpenFileName(this));
    QFile file(fileInfo.absoluteFilePath());
    file.open(QIODevice::ReadOnly);
    QByteArray bytes = file.readAll();
    InfoHead *infoHead = new InfoHead(bytes.size(), 1, Operation::SendImgMsg, Operation::Success,
                                      CONF.userId, reId, fileInfo.fileName());
    TRANS->writeTcp(infoHead, bytes, CONF.serverIp, CONF.tcpPort);
    QString picName = QString("%1-%2-%3").arg(QString::number(CONF.userId),
                                              QString::number(QDateTime::currentDateTime().toSecsSinceEpoch()),
                                              fileInfo.fileName());
    addJsonTools.setChatRoomList(this->chatDesk);
    addJsonTools.changeJsonFile(CONF.userId,"img",picName,infoHead->getDes(),infoHead->getSrc(),"img");
}


void Chatroom::reSendImgMsg(InfoHead *infoHead, QByteArray bytes, QHostAddress ip, quint16 port) {
    if (infoHead->getStateCode() == Operation::Fail) {
        qDebug() << "sendFail!!";
        return;
    }
    QFile imgFile(QString("%1/Qtuber/%2/img/%3").arg(CONF.localDataPath, QString::number(CONF.userId), infoHead->getFileName()));

    qDebug() << "reSend IMG PATH :" << QString("%1Qtuber/%2/img/%3").arg(CONF.localDataPath, QString::number(CONF.userId), infoHead->getFileName());

    imgFile.open(QIODevice::WriteOnly);
    imgFile.write(bytes);
    addJsonTools.setChatRoomList(this->chatDesk);
    qDebug() << "getFileName:::::" << infoHead->getFileName();
    addJsonTools.changeJsonFile(CONF.userId,"img",infoHead->getFileName(),infoHead->getSrc(),infoHead->getSrc(),"img");
}

void Chatroom::addNewWidget(QWidget *qWidget){
    QListWidgetItem * listItem = new QListWidgetItem(this->chatDesk);
    listItem->setSizeHint(qWidget->size());
    this->chatDesk->setItemWidget(listItem, qWidget);
    this->chatDesk->setCurrentRow(this->chatDesk->count()-1);
}

void Chatroom::setReId(qint32 reId) {
    this->reId = reId;
}

void Chatroom::clearMsg(){
    this->chatDesk->clear();
}

void Chatroom::sendFileMsg() {
    QFileInfo fileInfo(QFileDialog::getOpenFileName(this));
    QFile file(fileInfo.absoluteFilePath());
    file.open(QIODevice::ReadOnly);
    QByteArray bytes = file.readAll();
    InfoHead *infoHead = new InfoHead(bytes.size(), 1, Operation::SendFileMsg, Operation::Success,
                      CONF.userId, reId, fileInfo.fileName());
    TRANS->writeTcp(infoHead, bytes, CONF.serverIp, CONF.tcpPort);
    QString picName = QString("%1-%2-%3").arg(QString::number(CONF.userId),
                          QString::number(QDateTime::currentDateTime().toSecsSinceEpoch()),
                          fileInfo.fileName());

    addJsonTools.setChatRoomList(this->chatDesk);
    addJsonTools.changeJsonFile(CONF.userId, "file",picName, infoHead->getDes(), infoHead->getSrc(),"file");
}

void Chatroom::reSendFileMsg(InfoHead *infoHead, QByteArray bytes, QHostAddress ip, quint16 port) {
    if (infoHead->getStateCode() == Operation::Fail) {
        qDebug() << "sendFail!!";
        return;
    }

    QFile imgFile(QString("%1/Qtuber/%2/file/%3").arg(CONF.localDataPath, QString::number(CONF.userId), infoHead->getFileName()));
    imgFile.open(QIODevice::WriteOnly);
    imgFile.write(bytes);
    addJsonTools.setChatRoomList(this->chatDesk);
    addJsonTools.changeJsonFile(CONF.userId,"file", infoHead->getFileName(), infoHead->getSrc(),infoHead->getSrc(), "file");
}

